﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.Collections.ObjectModel;
using System.IO;

namespace Portal.CMS
{
    public class SyncServiceBll
    {
        public static string ConnectionString
        {
            get
            {
                return Environments.ConnectionString;// @"Data Source=.\SQLEXPRESS;Initial Catalog=Portal.Sodc.Online;Integrated Security=true;Pooling=true;Max Pool Size=10000;";
            }
        }

        public static string MediaPath
        {
            get
            {
                return Environments.WorkingPath + "\\Media\\" + Environments.PortalAlias;// @"E:\WEB.ONLINE\WorkingDir\Media\SODC";
            }
        }

        static bool CheckHasData(string TableName, string KeyField, string RecordId)
        {
            string Query = "select [" + KeyField + "] from [" + TableName + "] where [" + KeyField + "]=@RecordId";
            DataTable dtResult = new Portal.Database.SqlDatabase(ConnectionString).GetRecordSet(Query,
                new DatabaseParamCls[]{
                new DatabaseParamCls("RecordId",RecordId)
            });
            return dtResult.Rows.Count > 0;
        }


        static DataTable GetOrgStruct(string TableName)
        {
            DataTable dt = new Portal.Database.SqlDatabase(ConnectionString).GetRecordSet("select TOP 1 * from [" + TableName + "] where 1=2");
            return dt;
        }

        static DatabaseParamCls[] GetOneRowDatabaseParams(
            DataTable OrgDataTable,
            DataTable dtTable)
        {
            return GetOneRowDatabaseParams(OrgDataTable,dtTable,0);
        }


        static DatabaseParamCls[] GetOneRowDatabaseParams(
            DataTable OrgDataTable,
            DataTable dtTable,
            int RowIndex)
        {
            Collection<DatabaseParamCls> DatabaseParams = new Collection<DatabaseParamCls>();
            for (int iIndex = 0; iIndex < dtTable.Columns.Count; iIndex++)
            {
                string ColKey = (string)dtTable.Columns[iIndex].ColumnName;
                string Value = Portal.Database.DatabaseUtilities.GetString(dtTable.Rows[RowIndex], ColKey);
                object oValue = Value;
                //check datetime fields
                Type ColDataType = OrgDataTable.Columns[ColKey].DataType;
                SqlDbType sqltype = SqlDbType.NText;
                if (ColDataType == typeof(DateTime))
                {
                    sqltype = SqlDbType.DateTime;
                    DateTime ValueDate = DateTime.Parse(Value);
                    oValue = ValueDate;
                }

                if (ColDataType == typeof(int) || ColDataType == typeof(Int16) || ColDataType == typeof(Int32))
                {
                    sqltype = SqlDbType.Int;
                }
                if (ColDataType == typeof(decimal) || ColDataType == typeof(float))
                {
                    sqltype = SqlDbType.Decimal;
                }
                if (ColDataType == typeof(byte[]))
                {
                    sqltype = SqlDbType.Image;
                    oValue = Portal.Environment.Environments.GetBytesFromString(Value);
                }

                DatabaseParams.Add(new DatabaseParamCls(ColKey, sqltype, oValue));
            }
            DatabaseParamCls[] RetDatabaseParams = new DatabaseParamCls[DatabaseParams.Count];
            for (int iIndex = 0; iIndex < DatabaseParams.Count; iIndex++)
            {
                RetDatabaseParams[iIndex] = DatabaseParams[iIndex];
            }
            return RetDatabaseParams;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="GroupNewsId"></param>
        /// <param name="dtGroupNews"></param>
        static void SyncGroupNews(string GroupNewsId, DataTable dtGroupNews)
        {
            string TableName = "TableGroupNews";
            string KeyField = "GroupNewsId";

            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtGroupNews);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, GroupNewsId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   GroupNewsId,
                   DatabaseParams);
            }
        }


        public static void SyncGroupNewsItem(DataTable dtGroupNewsItem,byte[] oBytes1,byte[] oBytes2)
        {
            string TableName = "TableGroupNewsItem";
            string KeyField = "GroupNewsItemId";

            for (int iIndex = 0; iIndex < dtGroupNewsItem.Rows.Count; iIndex++)
            {
                string GroupNewsItemId = (string)dtGroupNewsItem.Rows[iIndex]["GroupNewsItemId"];
                DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtGroupNewsItem);
                //doan nay kiem tra xem co du lieu chua
                bool HasRecord = CheckHasData(TableName, KeyField, GroupNewsItemId);
                if (HasRecord == false)
                {
                    //doan nay chua co nhet vao
                    new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                        null,
                        ConnectionString,
                        TableName,
                        DatabaseParams);
                }
                else
                {
                    //doan nay chua co thi update
                    new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                       null,
                       ConnectionString,
                       TableName,
                       KeyField,
                       GroupNewsItemId,
                       DatabaseParams);
                }
            }
            string BelongSite = (string)dtGroupNewsItem.Rows[0]["BelongSite"];
            string GroupNewsId = (string)dtGroupNewsItem.Rows[0]["fk_GroupNews_Id"];
            System.IO.Directory.CreateDirectory(MediaPath);
            System.IO.Directory.CreateDirectory(MediaPath + "\\GroupNews");
            System.IO.Directory.CreateDirectory(MediaPath + "\\GroupNews\\Images");
            System.IO.Directory.CreateDirectory(MediaPath + "\\GroupNews\\Images\\" + GroupNewsId);
            System.IO.Directory.CreateDirectory(MediaPath + "\\GroupNews\\Images\\" + GroupNewsId+"\\"+BelongSite);

            string MediaPathSave = MediaPath + "\\GroupNews\\Images\\" + GroupNewsId + "\\" + BelongSite;

            if (oBytes1 != null)
            {
                string GroupNewsItemImage = (string)dtGroupNewsItem.Rows[0]["GroupNewsItemImage"];
                string FileSave1 = MediaPathSave + "\\" + GroupNewsItemImage;
                try
                {
                    System.IO.File.Delete(FileSave1);
                }
                catch { }
                Portal.Environment.Environments.SaveBytesToFile(FileSave1, oBytes1);
            }
            if (oBytes2 != null)
            {
                string GroupNewsItemLargeImage = (string)dtGroupNewsItem.Rows[0]["GroupNewsItemLargeImage"];
                string FileSave2 = MediaPathSave + "\\" + GroupNewsItemLargeImage;
                try
                {
                    System.IO.File.Delete(FileSave2);
                }
                catch { }
                Portal.Environment.Environments.SaveBytesToFile(FileSave2, oBytes2);
            }
        }


        public static void UnPublishingData(
            string TableName, 
            string KeyField, 
            string KeyId, 
            DatabaseParamCls[] DatabaseParams)
        {
            new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                  null,
                  ConnectionString,
                  TableName,
                  KeyField,
                  KeyId,
                  DatabaseParams);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="NewsId"></param>
        /// <param name="XmlData"></param>
        public static void SyncNews(string NewsId, string XmlData,byte[] oBytes1,byte[] oBytes2,byte[] oBytes3)
        {
            string TableName = "TableNews";
            string KeyField = "NewsId";
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(XmlData));

            DataTable dtGroupNews = ds.Tables[0];
            DataTable dtGroupNewsItem = ds.Tables[1];
            DataTable dtNews=ds.Tables[2];
            DataTable dtRelationNews = null;
            try
            {
                dtRelationNews = ds.Tables[3];
            }
            catch { }

            string GroupNewsId = Portal.Database.DatabaseUtilities.GetString(dtGroupNews.Rows[0], "GroupNewsId");
            SyncGroupNews(GroupNewsId, dtGroupNews);
            SyncGroupNewsItem(dtGroupNewsItem,null,null);

            //doan nay lam viec voi tablenews
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtNews);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, NewsId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   NewsId,
                   DatabaseParams);
            }
            //doan nay sync TableNewsRelation
            if (dtRelationNews != null)
            {
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteQuery(
                           null,
                           ConnectionString,
                           null,"Delete from TableNewsRelation where fk_News_Id='"+NewsId+"'");

                for (int iNewsRelation = 0; iNewsRelation < dtRelationNews.Rows.Count; iNewsRelation++)
                {
                    string NewsRelationId = dtRelationNews.Rows[iNewsRelation].ToString();
                    DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableNewsRelation"), dtRelationNews, iNewsRelation);
                    //doan nay kiem tra xem co du lieu chua
                    HasRecord = CheckHasData("TableNewsRelation", "NewsRelationId", NewsRelationId);
                    if (HasRecord == false)
                    {
                        //doan nay chua co nhet vao
                        new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                            null,
                            ConnectionString,
                            "TableNewsRelation",
                            DatabaseParams);
                    }
                    else
                    {
                        //doan nay chua co thi update
                        new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                           null,
                           ConnectionString,
                           "TableNewsRelation",
                           "NewsRelationId",
                           NewsRelationId,
                           DatabaseParams);
                    }
                }
            }

            //doan nay copy anh vao thu muc media...!
            string BelongSite = (string)dtNews.Rows[0]["BelongSite"];

            System.IO.Directory.CreateDirectory(MediaPath);
            System.IO.Directory.CreateDirectory(MediaPath + "\\News");
            System.IO.Directory.CreateDirectory(MediaPath + "\\News\\Images");
            System.IO.Directory.CreateDirectory(MediaPath + "\\News\\Images\\"+BelongSite);
            
            string MediaPathSave = MediaPath + "\\News\\Images\\"+BelongSite;
            //string FileLog = Environments.WorkingPath + "\\Log.txt";
            
            //System.IO.StreamWriter sw = System.IO.File.CreateText(FileLog);
            if (oBytes1 != null)
            {
               
                string ImageUrl=(string)dtNews.Rows[0]["ImageUrl"];
                string FileSave1 = MediaPathSave + "\\" + ImageUrl;
                try
                {
                    System.IO.File.Delete(FileSave1);
                }
                catch { }
                Portal.Environment.Environments.SaveBytesToFile(FileSave1, oBytes1);
               // sw.Write("oBytes1: " + oBytes1.Length + " filesaved: "+FileSave1);
            }
            if (oBytes2 != null)
            {
                string SmallImage = (string)dtNews.Rows[0]["SmallImage"];
                string FileSave2 = MediaPathSave + "\\" + SmallImage;
                try
                {
                    System.IO.File.Delete(FileSave2);
                }
                catch { }
                Portal.Environment.Environments.SaveBytesToFile(FileSave2, oBytes2);
                //sw.Write("oBytes2: " + oBytes2.Length + " filesaved: " + FileSave2);
            }

            //if (oBytes3 != null)
            {
                //sw.Write("oBytes3: " + oBytes3.Length);
                Portal.Environment.BobController.SaveBlobField(Environments.ConnectionString, "TableNews", "DocumentContent", "NewsId", NewsId, oBytes3);
            }
            //sw.Close();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="AdvImageId"></param>
        /// <param name="dtAdvImage"></param>
        static void SyncAdvImage(string AdvImageId, DataTable dtAdvImage)
        {
            string TableName = "TableAdvImage";
            string KeyField = "AdvImageId";

            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtAdvImage);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, AdvImageId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   AdvImageId,
                   DatabaseParams);
            }
        }

        public static void SyncAdvImageItem(string AdvImageItemId, string XmlData,byte[] oBytes1)
        {
            string TableName = "TableAdvImageItem";
            string KeyField = "AdvImageItemId";

            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(XmlData));

            DataTable dtAdvImage = ds.Tables[0];
            DataTable dtAdvImageItems = ds.Tables[1];

            string AdvImageId=
                Portal.Database.DatabaseUtilities.GetString(dtAdvImage.Rows[0],"AdvImageId");
            
            SyncAdvImage(AdvImageId, dtAdvImage);

            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtAdvImageItems);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, AdvImageItemId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   AdvImageItemId,
                   DatabaseParams);
            }

            //doan nay copy anh vao thu muc media...!
            string BelongSite = (string)dtAdvImageItems.Rows[0]["BelongSite"];

            System.IO.Directory.CreateDirectory(MediaPath);
            System.IO.Directory.CreateDirectory(MediaPath + "\\AdvImage");
            System.IO.Directory.CreateDirectory(MediaPath + "\\AdvImage\\Images");
            System.IO.Directory.CreateDirectory(MediaPath + "\\AdvImage\\Images\\" + BelongSite);
            System.IO.Directory.CreateDirectory(MediaPath + "\\AdvImage\\Images\\" + BelongSite+"\\"+AdvImageId);

            string MediaPathSave = MediaPath + "\\AdvImage\\Images\\" + BelongSite + "\\" + AdvImageId;

            if (oBytes1 != null)
            {
                string FileImage = (string)dtAdvImageItems.Rows[0]["FileImage"];
                string FileSave = MediaPathSave + "\\" + FileImage;
                try
                {
                    System.IO.File.Delete(FileSave);
                }
                catch { }
                Portal.Environment.Environments.SaveBytesToFile(FileSave, oBytes1);
            }
        }




        public static void SyncFocusNews(string FocusNewsId, string XmlData)
        {
            string TableName = "TableFocusNews";
            string KeyField = "FocusNewsId";

            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(XmlData));

            DataTable dtFocusNews = ds.Tables[0];
            DataTable dtFocusNewsItem = ds.Tables[1];



            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtFocusNews);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, FocusNewsId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   FocusNewsId,
                   DatabaseParams);
            }

            TableName = "TableFocusNewsItems";
            KeyField = "FocusNewsItemId";
            //doan nay sync focusnews item
            new Portal.Database.SqlDatabase(ConnectionString).ExecuteQuery(
                  null,
                  ConnectionString,new DatabaseParamCls[]{
                      new DatabaseParamCls("FocusNewsId",FocusNewsId)
                  },"Delete from TableFocusNewsItems where fk_FocusNews_Id=@FocusNewsId");

            //nhet lai
            
            for (int iIndex = 0; iIndex < dtFocusNewsItem.Rows.Count; iIndex++)
            {
                string FocusNewsItemId = (string)dtFocusNewsItem.Rows[iIndex]["FocusNewsItemId"];
                DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtFocusNewsItem,iIndex);
                //doan nay kiem tra xem co du lieu chua
                HasRecord = CheckHasData(TableName, KeyField, FocusNewsItemId);
                if (HasRecord == false)
                {
                    //doan nay chua co nhet vao
                    new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                        null,
                        ConnectionString,
                        TableName,
                        DatabaseParams);
                }
                else
                {
                    //doan nay chua co thi update
                    new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                       null,
                       ConnectionString,
                       TableName,
                       KeyField,
                       FocusNewsItemId,
                       DatabaseParams);
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="HtmlId"></param>
        /// <param name="XmlData"></param>
        public static void SyncHtml(string HtmlId, string XmlData)
        {
            string TableName = "TableHtml";
            string KeyField = "HtmlId";

            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(XmlData));

            DataTable dtHtml = ds.Tables[0];
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtHtml);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, HtmlId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   HtmlId,
                   DatabaseParams);
            }
        }

        static void SyncDocument(string DocumentId, DataTable dtDocument)
        {
            string TableName = "TableDocument";
            string KeyField = "DocumentId";

            DataSet ds = new DataSet();
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtDocument);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, DocumentId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   DocumentId,
                   DatabaseParams);
            }
        }

        public static void SyncDocumentItem(string DocumentItemId, string XmlData)
        {
            string TableName = "TableDocumentItem";
            string KeyField = "DocumentItemId";

            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(XmlData));

            DataTable dtDocument = ds.Tables[0];
            string DocumentId=(string)dtDocument.Rows[0]["DocumentId"];
            SyncDocument(DocumentId, dtDocument);
            DataTable dtDocumentItem = ds.Tables[1];
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtDocumentItem);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, DocumentItemId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   DocumentItemId,
                   DatabaseParams);
            }
        }




        static void SyncLawDocument(string LawDocumentId, DataTable dtLawDocument)
        {
            string TableName = "TableLawDocument";
            string KeyField = "LawDocumentId";

            DataSet ds = new DataSet();
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtLawDocument);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, LawDocumentId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   LawDocumentId,
                   DatabaseParams);
            }
        }


        static void SyncLawDocumentOffice(string LawDocumentOfficeId, DataTable dtLawDocumentOffice)
        {
            string TableName = "TableLawDocumentOffice";
            string KeyField = "LawDocumentOfficeId";

            DataSet ds = new DataSet();
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtLawDocumentOffice);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, LawDocumentOfficeId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   LawDocumentOfficeId,
                   DatabaseParams);
            }
        }


        static void SyncLawDocumentSigner(string LawDocumentSignerId, DataTable dtLawDocumentSigner)
        {
            string TableName = "TableLawDocumentSigner";
            string KeyField = "LawDocumentSignerId";

            DataSet ds = new DataSet();
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtLawDocumentSigner);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, LawDocumentSignerId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   LawDocumentSignerId,
                   DatabaseParams);
            }
        }



        static void SyncLawDocumentType(string LawDocumentTypeId, DataTable dtLawDocumentType)
        {
            string TableName = "TableLawDocumentType";
            string KeyField = "LawDocumentTypeId";

            DataSet ds = new DataSet();
            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtLawDocumentType);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, LawDocumentTypeId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   LawDocumentTypeId,
                   DatabaseParams);
            }
        }

        public static void SyncLawDocumentItem(string LawDocumentItemId, string XmlData)
        {
            string TableName = "TableLawDocumentItem";
            string KeyField = "LawDocumentItemId";

            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(XmlData));

            DataTable dtLawDocument = ds.Tables[0];
            string LawDocumentId = (string)dtLawDocument.Rows[0]["LawDocumentId"];
            SyncLawDocument(LawDocumentId, dtLawDocument);

            DataTable TableLawDocumentOffice = ds.Tables[1];
            DataTable TableLawDocumentSigner = ds.Tables[2];
            DataTable TableLawDocumentType = ds.Tables[3];
            string LawDocumentTypeId = (string)TableLawDocumentType.Rows[0]["LawDocumentTypeId"];
            string LawDocumentOfficeId = (string)TableLawDocumentOffice.Rows[0]["LawDocumentOfficeId"];
            string LawDocumentSignerId = (string)TableLawDocumentSigner.Rows[0]["LawDocumentSignerId"];

            SyncLawDocumentOffice(LawDocumentOfficeId, TableLawDocumentOffice);
            SyncLawDocumentSigner(LawDocumentSignerId, TableLawDocumentSigner);
            SyncLawDocumentType(LawDocumentTypeId, TableLawDocumentType);

            DataTable dtLawDocumentItem = ds.Tables[4];

            DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct(TableName), dtLawDocumentItem);
            //doan nay kiem tra xem co du lieu chua
            bool HasRecord = CheckHasData(TableName, KeyField, LawDocumentItemId);
            if (HasRecord == false)
            {
                //doan nay chua co nhet vao
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    null,
                    ConnectionString,
                    TableName,
                    DatabaseParams);
            }
            else
            {
                //doan nay chua co thi update
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteUpdateQuery(
                   null,
                   ConnectionString,
                   TableName,
                   KeyField,
                   LawDocumentItemId,
                   DatabaseParams);
            }
        }




        public static void SyncGroupLink(string GroupLinkId, string XmlData)
        {
            SqlConnection oSqlConnection = new SqlConnection(ConnectionString);
            oSqlConnection.Open();
            SqlTransaction sqlTrans = oSqlConnection.BeginTransaction();
            try
            {
                new Database.SqlDatabase().ExecuteQuery(
                    sqlTrans, Environments.ConnectionString, new DatabaseParamCls[]{
                    new DatabaseParamCls("GroupLinkId",GroupLinkId)
                },
                    " Delete from TableGroupLinkItem where fk_GroupLink_Id=@GroupLinkId;" +
                    " Delete from TableGroupLink where GroupLinkId=@GroupLinkId");

                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(XmlData));

                DataTable dtGroupLink = ds.Tables["TableGroupLink"];
                DataTable dtGroupLinkItem = null;
                if (ds.Tables["TableGroupLinkItem"] != null)
                {
                    dtGroupLinkItem = ds.Tables["TableGroupLinkItem"];
                }
                
                DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableGroupLink"), dtGroupLink);
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    sqlTrans,
                    ConnectionString,
                    "TableGroupLink",
                    DatabaseParams);
                //doan nay nhet item vao
                if (dtGroupLinkItem != null)
                {
                    for (int RowIndex = 0; RowIndex < dtGroupLinkItem.Rows.Count; RowIndex++)
                    {
                        DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableGroupLinkItem"), dtGroupLinkItem,RowIndex);
                        new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                            sqlTrans,
                            ConnectionString,
                            "TableGroupLinkItem",
                            DatabaseParams);
                    }
                }
                sqlTrans.Commit();
            }
            catch (Exception ex)
            {
                sqlTrans.Rollback();
                throw (ex);
            }
        }


        public static void SyncListNewsByGroup(string ListNewsByGroupId, string XmlData)
        {
            SqlConnection oSqlConnection = new SqlConnection(ConnectionString);
            oSqlConnection.Open();
            SqlTransaction sqlTrans = oSqlConnection.BeginTransaction();
            try
            {
                new Database.SqlDatabase().ExecuteQuery(
                    sqlTrans, Environments.ConnectionString, new DatabaseParamCls[]{
                    new DatabaseParamCls("ListNewsByGroupId",ListNewsByGroupId)
                },
                    " Delete from TableListNewsByGroupItem where fk_ListNewsByGroup_Id=@ListNewsByGroupId;" +
                    " Delete from TableListNewsByGroup where ListNewsByGroupId=@ListNewsByGroupId");

                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(XmlData));

                DataTable dtListNewsByGroup = ds.Tables["TableListNewsByGroup"];
                DataTable dtListNewsByGroupItem = null;
                if (ds.Tables["TableListNewsByGroupItem"] != null)
                {
                    dtListNewsByGroupItem = ds.Tables["TableListNewsByGroupItem"];
                }

                DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableListNewsByGroup"), dtListNewsByGroup);
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    sqlTrans,
                    ConnectionString,
                    "TableListNewsByGroup",
                    DatabaseParams);
                //doan nay nhet item vao
                if (dtListNewsByGroupItem != null)
                {
                    for (int RowIndex = 0; RowIndex < dtListNewsByGroupItem.Rows.Count; RowIndex++)
                    {
                        DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableListNewsByGroupItem"), dtListNewsByGroupItem, RowIndex);
                        new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                            sqlTrans,
                            ConnectionString,
                            "TableListNewsByGroupItem",
                            DatabaseParams);
                    }
                }
                sqlTrans.Commit();
            }
            catch (Exception ex)
            {
                sqlTrans.Rollback();
                throw (ex);
            }
        }



        public static void SyncAlbum(string AlbumId, string XmlData)
        {
            SqlConnection oSqlConnection = new SqlConnection(ConnectionString);
            oSqlConnection.Open();
            SqlTransaction sqlTrans = oSqlConnection.BeginTransaction();
            try
            {
                new Database.SqlDatabase().ExecuteQuery(
                    sqlTrans, Environments.ConnectionString, new DatabaseParamCls[]{
                    new DatabaseParamCls("AlbumId",AlbumId)
                },
                    " Delete from TableAlbumItem where fk_Album_Id=@AlbumId;" +
                    " Delete from TableAlbum where AlbumId=@AlbumId");

                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(XmlData));

                DataTable dtAlbum = ds.Tables["TableAlbum"];
                DataTable dtAlbumItem = null;
                if (ds.Tables["TableAlbumItem"] != null)
                {
                    dtAlbumItem = ds.Tables["TableAlbumItem"];
                }

                DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableAlbum"), dtAlbum);
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    sqlTrans,
                    ConnectionString,
                    "TableAlbum",
                    DatabaseParams);
                //doan nay nhet item vao
                if (dtAlbumItem != null)
                {
                    for (int RowIndex = 0; RowIndex < dtAlbumItem.Rows.Count; RowIndex++)
                    {
                        DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableAlbumItem"), dtAlbumItem, RowIndex);
                        new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                            sqlTrans,
                            ConnectionString,
                            "TableAlbumItem",
                            DatabaseParams);
                    }
                }
                sqlTrans.Commit();
            }
            catch (Exception ex)
            {
                sqlTrans.Rollback();
                throw (ex);
            }
        }


        public static void SyncVote(string VoteId, string XmlData)
        {
            SqlConnection oSqlConnection = new SqlConnection(ConnectionString);
            oSqlConnection.Open();
            SqlTransaction sqlTrans = oSqlConnection.BeginTransaction();
            try
            {
                new Database.SqlDatabase().ExecuteQuery(
                    sqlTrans, Environments.ConnectionString, new DatabaseParamCls[]{
                    new DatabaseParamCls("VoteId",VoteId)
                },
                    " Delete from TableVoteItem where fk_Vote_Id=@VoteId;" +
                    " Delete from TableVote where VoteId=@VoteId");

                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(XmlData));

                DataTable dtVote = ds.Tables["TableVote"];
                DataTable dtVoteItem = null;
                if (ds.Tables["TableVoteItem"] != null)
                {
                    dtVoteItem = ds.Tables["TableVoteItem"];
                }

                DatabaseParamCls[] DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableVote"), dtVote);
                new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                    sqlTrans,
                    ConnectionString,
                    "TableVote",
                    DatabaseParams);
                //doan nay nhet item vao
                if (dtVoteItem != null)
                {
                    for (int RowIndex = 0; RowIndex < dtVoteItem.Rows.Count; RowIndex++)
                    {
                        DatabaseParams = GetOneRowDatabaseParams(GetOrgStruct("TableVoteItem"), dtVoteItem, RowIndex);
                        new Portal.Database.SqlDatabase(ConnectionString).ExecuteInsertQuery(
                            sqlTrans,
                            ConnectionString,
                            "TableVoteItem",
                            DatabaseParams);
                    }
                }
                sqlTrans.Commit();
            }
            catch (Exception ex)
            {
                sqlTrans.Rollback();
                throw (ex);
            }
        }

    }
}
